package com.tl.sun.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.api.network.StringDialogCallback;
import com.tl.sun.model.BaseModel;
import com.tl.sun.ui.interfaces.VerifyHelper;
import com.tl.sun.utils.DeviceUuidFactory;
import com.tl.sun.utils.ToastUtil;
import com.tl.sun.utils.common.MD5Util;
import com.tl.sun.utils.common.RegularUtils;
import com.tl.sun.widgets.ButtonTimer;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/13.
 */

public class ReplacePhoneActivity extends BaseActivity {


    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.et_replace_phone)
    EditText mEtReplacePhone;
    @Bind(R.id.bt_send_code)
    ButtonTimer mBtSendCode;
    @Bind(R.id.et_replace_code)
    EditText mEtReplaceCode;
    @Bind(R.id.tv_replace_submit)
    TextView mTvReplaceSubmit;
    @Bind(R.id.iv_replace_verfiy)
    ImageView mIvReplaceVerfiy;
    @Bind(R.id.et_replace_verfiy)
    EditText mEtReplaceVerfiy;
    private String phone = "";
    private String phones = "";

    private String title;
    private String name;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_replace_phone);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            phones = bundle.getString("phone");
            name = bundle.getString("name");
        }
        init();
    }

    public void init() {
        if (!TextUtils.isEmpty(phones)) {
            title = "更换手机号";
        } else {
            title = "绑定手机号";
        }
        mTvGenericTitle.setText(title);
    }

    @Override
    protected void onStart() {
        super.onStart();
        VerifyHelper.getImgVerify(mIvReplaceVerfiy);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.rl_generic_back, R.id.bt_send_code, R.id.tv_replace_submit, R.id.iv_replace_verfiy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_generic_back:
                onBackPressed();
                break;
            case R.id.iv_replace_verfiy:
                VerifyHelper.getImgVerify(mIvReplaceVerfiy);
                break;
            case R.id.bt_send_code:
                phone = mEtReplacePhone.getText().toString();
                String verfiy = mEtReplaceVerfiy.getText().toString();
                if (!TextUtils.isEmpty(phone)) {
                    if (RegularUtils.isMobileExact(phone)) {
                        if (EmptyUtils.isNotEmpty(verfiy)) {
                            getCode(phone, verfiy);
                        } else {
                            ToastUtil.showToast(getString(R.string.et_is_verify_empty));
                        }
                    } else {
                        ToastUtil.showToast("手机号格式不正确!");
                    }

                } else {
                    ToastUtil.showToast("手机号不能为空!");
                }
                break;
            case R.id.tv_replace_submit:
                phone = mEtReplacePhone.getText().toString();
                String code = mEtReplaceCode.getText().toString();
                if (!TextUtils.isEmpty(phone)) {
                    if (RegularUtils.isMobileExact(phone)) {
                        if (!TextUtils.isEmpty(code)) {
                            bindPhone(phone, code);
                        } else {
                            ToastUtil.showToast("验证码不能为空!");
                        }
                    } else {
                        ToastUtil.showToast("手机号格式不正确!");
                    }

                } else {
                    ToastUtil.showToast("手机号不能为空!");
                }
                break;
        }
    }

    public void getCode(String phone, String verfiy) {
        HashMap<String, String> map = new HashMap<>();
        map.put("num", phone);
        map.put("code", "rst_pass");
        map.put("verify", verfiy);
        JSONObject json = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this))
                .post(AppContext.getInstance().getBaseUrl() + "account/get_code_new")
                .tag(ReplacePhoneActivity.this)
                .upJson(json.toString())
                .execute(new StringDialogCallback(ReplacePhoneActivity.this, "加载中...", true) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            mBtSendCode.setTimes(60);
                            if (!mBtSendCode.isRun()) {
                                mBtSendCode.beginRun();
                                mBtSendCode.setEnabled(false);
                            }
                            ToastUtil.showToast(baseModel.getMsg());
                        } else {
                            VerifyHelper.getImgVerify(mIvReplaceVerfiy);
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });

    }

    public void bindPhone(String phone, String code) {
        HashMap map = new HashMap();
        map.put("version", AppContext.version);
        map.put("username", name);
        map.put("phone", phone);
        map.put("phone_code", code);
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        JSONObject json = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this)).post(AppContext.getInstance().getBaseUrl() + "account/set_phone")
                .tag(ReplacePhoneActivity.this)
                .upJson(json.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            if (!TextUtils.isEmpty(phones)) {
                            } else {
                                Intent bind = new Intent(ReplacePhoneActivity.this, BindPhoneSuccessActivity.class);
                                startActivity(bind);
                            }
                            finish();
                        } else {
                            VerifyHelper.getImgVerify(mIvReplaceVerfiy);
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }

                });
    }


}
